<?php
/**
 * Mechanism
 * 
 * LICENSE
 * 
 * This file is private intellectual property of the author. 
 * All rights reserved. Copying and illegal using is punishable by law.
 * 
 * @copyright Copyright (c) 2011 BreatheInMyVoid ( BreatheInMyVoid@gmail.com )
 */

namespace Mechanism\Director {
	use Mechanism\Loader,
		Mechanism\Router\IRouter,
		Mechanism\Request\IRequest;

	class Standart extends Director {
		public function direct( IRequest $request ) {
			if ( null === $this->app_path ) {
				throw new Exception\Logic( 'Application path is null' );
			}
			
			/* Routing */
			$this->router->route( $request->get_server( 'REQUEST_URI' ) );

			/* Load requested controller */
			$loader = new Loader\Resource\Controller( $this->app_path );
			$controller = $loader->load( $this->router->get_controller( ), 
										 $this->router->get_module( ) );
										 
			/* Load requesed action */
			$action = $this->router->get_action( ) . '_action';

			/* Invoke action and get response */
			if ( method_exists( $controller, $action ) ) {
				$response = $controller->$action( );
				
				/* Return response or null */
				if ( null === $response ) {
					return null;
				} else if ( !array_key_exists( 'Mechanism\Response\IResponse', 
								class_implements( ( object ) $response, false ) ) ) {
					throw new Exception\Runtime( 'Controller action should return  
												  Mechanism\Response\IResponse 
												  object or null' );
				} else {
					return $response;
				}
			} else {
				throw new Exception\Nonest( 'Can\'t find requested action
											 in the requested controller' );
			}			 
		}
	}	
}